import 'package:flutter/material.dart';
import 'package:videotop/base_model.dart';
import 'package:videotop/jsonbean/matchs.dart';
import 'package:videotop/myinfo.dart';
import 'package:videotop/sql/databasehelper.dart';
import 'package:videotop/sql/msg_table.dart';
import 'package:videotop/sql/user_table.dart';
import 'package:videotop/util.dart';
import 'package:videotop/widget/buyvip.dart';
import 'package:videotop/widget/spacePage.dart';

import '../evenbus.dart';

/// created by hx
///    2021/1/26:10:02

class MessageModel extends BaseModel{

  Util util;
  MyInfo myInfo;
  BuildContext context;
  MessageModel(this.util,this.myInfo,this.context);

  var db = DatabaseHelper();
  List<UserTable> list_v = [];
  List<Msg> list_msg = [];
  List<int> state = [];
  List<MatchedUsers> listmatch = [];
  int page = 1;
  ScrollController controller = ScrollController();
  bool loading = false;

  getInit(){
    getMatch();
    queryMsg();
    bus.on('refresh', (arg) {
      queryMsg();
    });
    bus.on('pairsum', (arg) {
      getMatch();
    });

    controller.addListener(() {
      if (controller.position.pixels == controller.position.maxScrollExtent) {
        page++;
        getMatch();
      }
    });
  }

  //匹配
  Future<Null> getMatch() async {
    try {
      if (page == 1) listmatch.clear();
      List<MatchedUsers> newlike = await util.getMatchData(page,myInfo.uid);
      listmatch.addAll(newlike);
      notifyListeners();
    } catch (e) {
      print(e);
    }
  }

  //查询Msg
  Future<Null> queryMsg() async {
    //消息
    List<Msg> listmsg = new List<Msg>();
    //用户
    List<UserTable> listuser = new List<UserTable>();
    //角标
    List<int> listint = new List<int>();

    List datas = await db.getNewUid();

    int count = 0;
    //角标总数
    for (int i = 0; i < datas.length; i++) {
      Msg dataListBean = Msg.fromMap(datas[i]);
      listmsg.add(dataListBean);

      //每个人的角标
      int pos = await db.getCountState(dataListBean.uid);
      count += pos;
      listint.add(pos);
      //查询User
      UserTable user = await db.getItem(dataListBean.uid);
      listuser.add(user);
    }

    bus.emit('count', count);
    loading = true;
    list_msg.clear();
    list_v.clear();
    state.clear();
    list_msg.addAll(listmsg);
    list_v.addAll(listuser);
    state.addAll(listint);
    notifyListeners();

  }

  matchTop(int index){
    if (myInfo.vip != 0) {
      print(listmatch[index].muid);
      Navigator.of(context)
          .push(MaterialPageRoute(
          builder: (context) => Space(
            uid: listmatch[index].muid,
          )));
    } else {
      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return BuyVip(index: 1,);
        },
      );
    }
  }
}